package com.blue.jdbc.annotation;

import com.blue.core.file.ClassScanner;
import com.blue.jdbc.dialect.IDialect;
import com.blue.jdbc.sql.SqlExtendUtil;
import com.blue.jdbc.sql.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.util.List;

/**
 * 解析Jdbc table => bean 映射
 *
 * @author zhengjin
 * @since 1.0 2018年12月03日
 */
public class JdbcTablePostProcessor implements BeanFactoryPostProcessor, InitializingBean
{
	private static Logger logger = LoggerFactory.getLogger(JdbcTablePostProcessor.class);

	private List<String> packageList;
	
	public JdbcTablePostProcessor()
	{
	}

	private Parser initParser(ConfigurableListableBeanFactory beanFactory)
	{
		IDialect dialect = beanFactory.getBean(IDialect.class);
		Parser parser = Parser.getInstance();
		SqlUtil sqlUtil = SqlUtil.getInstance();
		SqlExtendUtil sqlExtendUtil = SqlExtendUtil.getInstance();
		parser.setSqlUtil(sqlUtil);
		sqlUtil.setDialect(dialect);
		sqlExtendUtil.setDialect(dialect);
		return parser;
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
	{
		Parser parser = this.initParser(beanFactory);
		logger.info("初始化 Table 解析");
		String[] names = beanFactory.getBeanNamesForAnnotation(Table.class);
		for (String name : names)
		{
			BeanDefinition definition = beanFactory.getBeanDefinition(name);
			definition.setLazyInit(true);
			try
			{
				Class<?> clazz = Class.forName(definition.getBeanClassName());
				parser.parse(clazz);
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
		}
	}

	public void setScanPackages(List<String> packageList)
	{
		this.packageList = packageList;
	}

	@Override
	public void afterPropertiesSet() throws Exception
	{
		if (packageList == null || packageList.isEmpty())
			return;

		logger.info("扫描包：{}", packageList);

		ClassScanner scanner = new ClassScanner();
		scanner.setClassHandler(new JdbcTableClassHandler());
		scanner.scan(true, packageList);
	}
}
